/**
 * created by 小卷毛, 2020-05-15 015
 * Copyright (c) 2020, 416143467@qq.com All Rights Reserved.
 * #                   *********                            #
 * #                  ************                          #
 * #                  *************                         #
 * #                 **  ***********                        #
 * #                ***  ****** *****                       #
 * #                *** *******   ****                      #
 * #               ***  ********** ****                     #
 * #              ****  *********** ****                    #
 * #            *****   ***********  *****                  #
 * #           ******   *** ********   *****                #
 * #           *****   ***   ********   ******              #
 * #          ******   ***  ***********   ******            #
 * #         ******   **** **************  ******           #
 * #        *******  ********************* *******          #
 * #        *******  ******************************         #
 * #       *******  ****** ***************** *******        #
 * #       *******  ****** ****** *********   ******        #
 * #       *******    **  ******   ******     ******        #
 * #       *******        ******    *****     *****         #
 * #        ******        *****     *****     ****          #
 * #         *****        ****      *****     ***           #
 * #          *****       ***        ***      *             #
 * #            **       ****        ****                   #
 */
package com.aifeng.viewmodel

import com.aifeng.common_ui.helper.*
import com.aifeng.model.*
import com.aifeng.utils.applyCompletableSchedulers
import com.aifeng.utils.applyFlowableSchedulers
import com.aifeng.utils.applySchedulers
import com.aifeng.utils.subscribeByFinally
import com.lzg.extend.BaseResponse
import com.lzg.extend.jackson.JacksonConvert
import com.lzg.okrx.RxSingleHelper
import com.lzg.okrx.adapter.FlowableBody
import com.lzy.okgo.OkGo
import io.reactivex.Completable
import io.reactivex.Flowable
import io.reactivex.Single
import java.util.concurrent.TimeUnit

/**
 * 项目名称：Hassan_Food
 * 创建人：小卷毛
 * 创建时间：2020-05-15 14:16
 */
class OrderViewModel : BaseViewModel() {

    fun cancelRequest() = mDisposables.clear()

    fun delay(time: Long = 300, onResult: () -> Unit) =
        Completable.timer(time, TimeUnit.MILLISECONDS)
            .compose(applyCompletableSchedulers())
            .subscribe { onResult() }

    fun countDown(count: Long = 180): Flowable<Long> =
        Flowable.intervalRange(0, count + 1, 0, 1, TimeUnit.SECONDS)
            .compose(applyFlowableSchedulers())

    fun orderList(
        page: Int,
        state: String,
        userId: String,
        onSuccess: (ArrayList<OrderData>) -> Unit = {},
        onFinally: () -> Unit = {}
    ) =
        mDisposables.add(
            OkGo.post<BaseResponse<OrderModel>>(BaseUrl.orderList)
                .params(
                    getParams(
                        "page" to page,
                        "state" to state,
                        "userid" to userId
                    )
                )
                .converter(object : JacksonConvert<BaseResponse<OrderModel>>() {})
                .adapt(FlowableBody())
                .compose(applyFlowableSchedulers())
                .map { it.data.results }
                .subscribeByFinally(
                    event = this,
                    onSuccess = { onSuccess(it) },
                    onFinally = { onFinally() }
                )
        )

    fun orderDetail(orderId: String, userId: String) =
        OkGo.post<BaseResponse<OrderModel>>(BaseUrl.orderInfo)
            .params(
                getParams(
                    "id" to orderId,
                    "userid" to userId
                )
            )
            .converter(object : JacksonConvert<BaseResponse<OrderModel>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .doOnSubscribe { showLoading() }
            .doFinally { dismissLoading() }
            .map { it.data }

    fun orderHandle(url: String, orderId: String, userId: String) =
        RxSingleHelper.requestString(
            url = url,
            params = getParams(
                "userid" to userId,
                "id" to orderId
            )
        )
            .compose(applySchedulers())
            .doOnSubscribe { showLoading() }
            .doFinally { dismissLoading() }

    fun payOption(num: String, type: String, pwd: String = "") =
        RxSingleHelper.requestString(
            url = BaseUrl.prePay,
            params = getParams(
                "orderno" to num,
                "payment" to type,
                "paypwd" to pwd
            )
        )
            .compose(applySchedulers())
            .doOnSubscribe { showLoading() }
            .doFinally { dismissLoading() }

    fun shopList(page: Int, userId: String): Flowable<OrderModel> =
        OkGo.post<BaseResponse<OrderModel>>(BaseUrl.shopList)
            .params(
                getParams(
                    "page" to page,
                    "userid" to userId
                )
            )
            .converter(object : JacksonConvert<BaseResponse<OrderModel>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .map { it.data }

    fun userInfo(userId: String): Single<String> =
        RxSingleHelper.requestString(
            url = BaseUrl.getUserInfo,
            params = getParams("userid" to userId)
        )
            .compose(applySchedulers())
            .doOnSubscribe { showLoading() }
            .doFinally { dismissLoading() }

    fun inviteList(
        state: String,
        userId: String,
        onSuccess: (ShareModel) -> Unit = {},
        onFinally: () -> Unit = {}
    ) =
        mDisposables.add(
            OkGo.post<BaseResponse<ShareModel>>(BaseUrl.inviteList)
                .params(
                    getParams(
                        "state" to state,
                        "userid" to userId
                    )
                )
                .converter(object : JacksonConvert<BaseResponse<ShareModel>>() {})
                .adapt(FlowableBody())
                .compose(applyFlowableSchedulers())
                .map { it.data }
                .subscribeByFinally(
                    event = this,
                    onSuccess = { onSuccess(it) },
                    onFinally = { onFinally() }
                )
        )

    fun inviteAgree(id: String): Single<String> =
        RxSingleHelper.requestString(
            url = BaseUrl.editState,
            params = getParams("id" to id)
        )
            .compose(applySchedulers())
            .doOnSubscribe { showLoading() }
            .doFinally { dismissLoading() }

    fun sale(userId: String): Single<String> =
        RxSingleHelper.requestString(
            url = BaseUrl.saleInfo,
            params = getParams("userid" to userId)
        )
            .compose(applySchedulers())

    fun historyList(time: String): Flowable<ArrayList<CommonData>> =
        Flowable.just(time)
            .map {
                val items = ArrayList<CommonData>()

                if (it.isNotEmpty()) {
                    var start = it.toNotLong().getTimeString("yyyy-MM-dd")
                    val end = TimeHelper.getInstance().dayOfMonthFirst

                    while (start.isBefore(end)) {
                        items.add(
                            CommonData(
                                title = "${TimeHelper.getInstance().getYearOfDate(start)}年",
                                content = "${TimeHelper.getInstance().getMonthOfDate(start)}月",
                                create_date = start.toFormat("yyyy-MM-dd", "yyyy-MM")
                            )
                        )

                        start = TimeHelper.getInstance().getAfterMonth(start, 1)
                    }

                    items.reverse()
                }

                return@map items
            }
            .compose(applyFlowableSchedulers())

    fun historyDetail(date: String, userId: String): Single<String> =
        RxSingleHelper.requestString(
            url = BaseUrl.monthSale,
            params = getParams(
                "userid" to userId,
                "date" to date
            )
        )
            .compose(applySchedulers())
            .doOnSubscribe { showLoading() }
            .doFinally { dismissLoading() }

    fun expressList(num: String, show: Boolean = true) =
        OkGo.post<BaseResponse<ArrayList<ExpressData>>>(BaseUrl.express)
            .params(getParams("expressno" to num))
            .converter(object : JacksonConvert<BaseResponse<ArrayList<ExpressData>>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .doOnSubscribe { if (show) showLoading() }
            .doFinally { if (show) dismissLoading() }
            .map { it.data }

}